import { InjectRedis } from '@liaoliaots/nestjs-redis'
import { Injectable } from '@nestjs/common'
import Redis from 'ioredis'

@Injectable()
export class RedisService {
	constructor(@InjectRedis() private readonly client: Redis) {}

	getClient(): Redis {
		return this.client
	}
	/**
	 * redis基本信息
	 * @returns
	 */
	async getInfo() {
		// 连接到 Redis 服务器
		const rawInfo = await this.client.info()
		// 按行分割字符串
		const lines = rawInfo.split('\r\n')
		const parsedInfo = {}
		// 遍历每一行并分割键值对
		lines.forEach((line) => {
			const [key, value] = line.split(':')
			parsedInfo[key?.trim()] = value?.trim()
		})
		return parsedInfo
	}

	/**
	 *
	 * @param key 存储 key 值
	 * @param val key 对应的 val
	 * @param ttl 可选，过期时间，单位 毫秒
	 */
	async setString(key: string, val: any, ttl?: number): Promise<'OK' | null> {
		const data = JSON.stringify(val)
		if (!ttl) return await this.client.set(key, data)
		return await this.client.set(key, data, 'PX', ttl)
	}
	/**
	 * 返回对应 value
	 * @param key
	 */
	async getString(key: string): Promise<any> {
		if (!key || key === '*') return null
		const res = await this.client.get(key)
		return JSON.parse(res)
	}

	async del(keys: string | string[]): Promise<number> {
		if (!keys || keys === '*') return 0
		if (typeof keys === 'string') keys = [keys]
		return await this.client.del(...keys)
	}
}
